<?php
/**
 * Created by PhpStorm.
 * User: gk
 * Date: 18-9-13
 * Time: 下午10:22
 */

namespace addons\hlapp\model;


use addons\hlapp\dto\PageInfo;
use think\Model;
use think\model\concern\SoftDelete;
class CommonModel extends Model
{
    use SoftDelete;

    public $pageSize = 10;
    public $pageIndex = 1;

    protected $dateFormat = 'Y-m-d H:i';
    protected $deleteTime = 'delete_time';
    protected $autoWriteTimestamp = true;


    /**
     * 添加或修改
     * 返回id
     * @param $fields
     * @return false|int
     */
    public function saveOrUpdata($fields)
    {
        $this->allowField(true);
        if(array_key_exists('id',$fields)){
           $r = $this->save($fields,['id'=>$fields['id']]);
           if ($r){
               return $fields['id'];
           }else{
               return 0;
           }
        }else{
           $this->save($fields);
           return $this->getLastInsID();
        }
    }

    /**
     * 查询分页
     * @param int $pageIndex 第几页
     * @param int $pageSize 分页大小
     * @param null $whereArr 查询条件
     * @return PageInfo
     */
    public function getPage($whereSql=null,$withModel=null)
    {
        if(array_key_exists('pageIndex',$_POST)){
            $pageIndex = $_POST["pageIndex"];
        }else{
            $pageIndex = $this->pageIndex;
        }
        if(array_key_exists('pageMaxSize',$_POST)){
            $pageSize = $_POST['pageMaxSize'];
        }else{
            $pageSize = $this->pageSize;
        }
        if ($pageIndex == null && $pageIndex < 1) {
            $pageIndex = 1;
        }
        if ($withModel){
            $m = $this->with($withModel);
        }else{
            $m = $this;
        }
        $pageList = $m->where($whereSql)->page($pageIndex,$pageSize)->select();
        $count = $this->getCount($whereSql);
        $result = PageInfo::setPage($pageIndex, $pageSize, $pageList, $count);
        return $result;
    }

    /**
     * 查询总数
     * @param $whereSql
     * @return int|string
     */
    public function getCount($whereSql='')
    {
        return $this->where($whereSql)->count();
    }
}